﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Duality;
using Duality.Components;
using Duality.Components.Renderers;
using Duality.Resources;
using OpenTK;

namespace PhoenixCrab.MapTiles
{
    [Serializable]
    public class TileMapDisplay : Component, ICmpUpdatable, ICmpInitializable
    {
        /// <summary>
        /// The Map to display
        /// </summary>
        public ContentRef<TileMap> Map { get; set; }

        /// <summary>
        /// Whether this display of map is currently updated
        /// </summary>
        public bool Updated { get; set; }

        private void MapUpdate()
        {
            if (Map == null) return;

            GameObject mg = Scene.Current.FindGameObject("MapGrid");
            if (mg == null)
            {
                mg = new GameObject("MapGrid");
                Scene.Current.AddObject(mg);
            }

            for (int x = 0; x < Map.Res.Map.Count; x++)
            {
                for (int y = 0; y < Map.Res.Map[x].Count; y++)
                {
                    GameObject g = mg.ChildByName("Tile[" + x + "][" + y + "]");

                    if (g == null)
                    {
                        g = new GameObject(GameRes.Data.Tile_A_Prefab);  //Map.Res.Map[x][y].Res);
                        g.Parent = mg;
                        g.Name = "Tile[" + x + "][" + y + "]";
                        g.Active = true;
                        Scene.Current.AddObject(g);
                    }

                    Vector2 ts = new Vector2();
                    ts = Map.Res.TileSize;

                    g.GetComponent<Transform>().RelativePos = new Vector3(x * ts.X, y * ts.Y, 0);
                }
            }

            Updated = true;
        }

        public void OnUpdate()
        {
            if(!Updated)
                MapUpdate();
        }

        public void OnInit(InitContext context)
        {
            if(context == InitContext.AddToGameObject)
                MapUpdate();
        }

        public void OnShutdown(ShutdownContext context)
        {
            //throw new NotImplementedException();
        }

    }
}